package com.znyj.cloud.device.pack;

import com.alibaba.fastjson.JSONObject;
import com.znyj.cloud.chain.util.ByteUtil;
import com.znyj.cloud.device.constant.SysConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.zip.CRC32;

/**
 * Created by gaoliwei02 on 17/5/30.
 */

public class ReportSendPackage extends BasePackage {
    private static final Logger logger = Logger.getLogger(ReportSendPackage.class);
    //回复消息
    private String returnMsg;
    //这次汇报时间
    private Timestamp reportTime;

    private String deviceId;

    public ReportSendPackage(String deviceId) {
        this.deviceId = deviceId;
    }

    public String reportJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("returnMsg",returnMsg);
        jsonObject.put("reportTime",reportTime);
        jsonObject.put("deviceId",deviceId);
        return jsonObject.toString();
    }

    public void generateAndSendPackage(ChannelHandlerContext ctx) {
        returnMsg = "ok";
        reportTime = new Timestamp(System.currentTimeMillis());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(SysConstant.REPORT_KEY.MSG_TYPE, SysConstant.PACKAGE_VALUE.HEARTBEAT_RES_SENT);
        jsonObject.put(SysConstant.REPORT_KEY.DEVICE_ID, String.valueOf(deviceId));
        jsonObject.put(SysConstant.REPORT_KEY.HS_MSG, returnMsg);
        jsonObject.put(SysConstant.REPORT_KEY.RECEIVE_TIME, reportTime);

        byte[] json_byte = new byte[0];
        try {
            json_byte = jsonObject.toString().getBytes("ASCII");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        setPayloadData(json_byte);
        setJsonObject(jsonObject);

        setVersion(SysConstant.HEAD.VERSION_1);
        setFormat(SysConstant.HEAD.FORMAT_JSON);
        setReserved(SysConstant.HEAD.RESERVE);

        CRC32 crc32 = new CRC32();
        crc32.update(getPayloadData());
        int tempCRC = (int) crc32.getValue();
        crc32.reset();

        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(ByteUtil.intTointBIG(SysConstant.HEAD.PROTOCOL_HEAD));
        buf.writeInt(ByteUtil.intTointBIG(tempCRC));
        buf.writeInt(ByteUtil.intTointBIG(getVersion()));
        buf.writeInt(ByteUtil.intTointBIG(getFormat()));
        buf.writeInt(ByteUtil.intTointBIG(getReserved()));
        buf.writeInt(ByteUtil.intTointBIG(getPayloadData().length));
        buf.writeBytes(getPayloadData());
        try {
            ctx.writeAndFlush(buf);
        } catch (Exception e) {
            logger.error("writeAndFlushError", e);
        }
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
}
